import { ref, onMounted, onBeforeUnmount } from 'vue'

export default function useFullscreen(target?: HTMLElement | null) {
  const isFullscreen = ref<boolean>(!!document.fullscreenElement)

  const requestFs = () => {
    const el = target ?? document.documentElement
    const anyEl = el as any
    const fn =
      anyEl.requestFullscreen ||
      anyEl.webkitRequestFullscreen ||
      anyEl.msRequestFullscreen ||
      anyEl.mozRequestFullScreen
    return fn?.call(anyEl)
  }

  const exitFs = () => {
    const d = document as any
    const fn =
      d.exitFullscreen ||
      d.webkitExitFullscreen ||
      d.msExitFullscreen ||
      d.mozCancelFullScreen
    return fn?.call(d)
  }

  const toggleFullscreen = async () => {
    try {
      if (isFullscreen.value) {
        await exitFs()
      } else {
        await requestFs()
      }
    } catch (e) {
      console.error('Fullscreen toggle failed:', e)
    }
  }

  const onFsChange = () => {
    isFullscreen.value = !!document.fullscreenElement
  }

  onMounted(() => {
    document.addEventListener('fullscreenchange', onFsChange)
    document.addEventListener('webkitfullscreenchange', onFsChange as any)
    document.addEventListener('mozfullscreenchange', onFsChange as any)
    document.addEventListener('MSFullscreenChange', onFsChange as any)
  })

  onBeforeUnmount(() => {
    document.removeEventListener('fullscreenchange', onFsChange)
    document.removeEventListener('webkitfullscreenchange', onFsChange as any)
    document.removeEventListener('mozfullscreenchange', onFsChange as any)
    document.removeEventListener('MSFullscreenChange', onFsChange as any)
  })

  return {
    isFullscreen,
    enter: requestFs,
    exit: exitFs,
    toggleFullscreen,
  }
}